package com.jz.digital.gongxu

import android.app.Activity
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.text.InputType
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import android.widget.PopupWindow
import com.jz.digital.R
import com.jz.digital.base.BaseClickActivity
import com.jz.digital.bean.ServerBean
import com.jz.digital.dialog.DialogUtil
import com.jz.digital.scan.ScanCodeActivity
import com.jz.digital.utils.AppUtil
import com.jz.digital.utils.DataUtil
import com.jz.digital.utils.systembar.ImmersionBar
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_ban_zu
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_bottom_buliang_yuanying
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_bottom_ji_tai
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_buliang_shuliang
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_gong_dan
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_gong_dan_liang
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_gong_yi
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_gui_ge
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_ke_hu
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_liangpin_shuliang
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_main_gong_xu
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_pin_ming
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_po
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_scan
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_xing_hao
import kotlinx.android.synthetic.main.activity_gong_xu_layout.label_yibao_gongdan
import kotlinx.android.synthetic.main.activity_gong_xu_layout.sv_parent
import kotlinx.android.synthetic.main.activity_gong_xu_layout.tv_commit
import kotlinx.android.synthetic.main.activity_gong_xu_pre_layout.cml_ban_zu
import kotlinx.android.synthetic.main.activity_gong_xu_pre_layout.cml_gong_yi
import kotlinx.android.synthetic.main.activity_gong_xu_pre_layout.label_gong_xu
import kotlinx.android.synthetic.main.activity_gong_xu_pre_layout.label_ji_tai
import kotlinx.android.synthetic.main.layout_common_title.layout_parent

/**
 * @author jiangdz
 * @date 2024/11/19
 * @time 19:26
 * 用途:工序汇报
 */
class GongXuCommitActivity : BaseClickActivity<GongXuCommitPresenter>(),
    IGongXuCommitView {
    private var mGongXuPopupWindow: PopupWindow? = null
    private var mJiTaiPopupWindow: PopupWindow? = null
    private var mGongYiPopupWindow: PopupWindow? = null
    private var mBanZuPopupWindow: PopupWindow? = null
    private var mTeamGroupPopupWindow: PopupWindow? = null
    private var mGX = ""
    private var mNo7 = ""
    private var mNo8 = ""
    private var mNo10 = ""

    /**
     * 工单输入框焦点
     */
    private var mOrderEditFocus = false
    override fun getLayoutResId(): Int {
        return R.layout.activity_gong_xu_layout
    }

    override fun initViews() {
        super.initViews()
        ImmersionBar.with(this).statusBarColor(R.color.main_color)
            .titleBarMarginTop(layout_parent)
            .init()
        setTitle(R.string.gongxu_huibao)
        mTitleBar.getTitleLayoutAll(this).setBackgroundColor(getColor(R.color.main_color))
        mTitleBar.setLeftImgTint(ColorStateList.valueOf(Color.WHITE))
        mTitleBar.setTitleColor(Color.WHITE)
        label_scan?.getRightImage()?.setOnClickListener {
            clearShowContent()
            startActivityForResult(
                Intent(this@GongXuCommitActivity, ScanCodeActivity::class.java),
                scanRequestCode
            )
        }
    }

    override fun initListening() {
        super.initListening()
        label_liangpin_shuliang?.getEditWidget()?.inputType = InputType.TYPE_CLASS_NUMBER
        label_buliang_shuliang?.getEditWidget()?.inputType = InputType.TYPE_CLASS_NUMBER
        tv_commit?.setOnClickListener(this)
        label_gong_xu?.setOnClickListener(this)
        label_ji_tai?.setOnClickListener(this)
        cml_gong_yi?.setOnClickListener(this)
        cml_ban_zu?.setOnClickListener(this)
        label_bottom_buliang_yuanying?.getRightImage()?.setOnClickListener(this)
        label_scan?.getEditWidget()?.gravity = Gravity.END
        label_scan?.getEditWidget()?.onFocusChangeListener =
            OnFocusChangeListener { p0, p1 ->
                mOrderEditFocus = p1
                if (!p1) {
                    commit(false)
                } else {
                    clearBackContent()
                }
            }
        // 处理 ScrollView 的触摸事件，使 EditText 失去焦点
        sv_parent.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_MOVE) {
                // 隐藏软键盘并清除 EditText 焦点
                if (mOrderEditFocus) {
                    label_scan?.getEditWidget()?.clearFocus()
                }
            }
            false
        }
        label_liangpin_shuliang?.getEditWidget()?.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                label_liangpin_shuliang?.getEditWidget()?.setText("")
            }
        }
        label_buliang_shuliang?.getEditWidget()?.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                label_buliang_shuliang?.getEditWidget()?.postDelayed({
                    label_buliang_shuliang?.getEditWidget()
                        ?.setSelection(label_buliang_shuliang?.getEditWidget()?.text?.length ?: 0)
                },100)
            }
        }
    }

    override fun initData() {
        super.initData()
        mPresenter.initData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == scanRequestCode) {
            val barCode = data?.getStringExtra(ScanCodeActivity.KEY_DATA) ?: ""
            if (barCode.isNullOrEmpty()) return
            label_scan?.getEditWidget()?.setText(barCode)
            commit(false)
        }
    }

    override fun clickAction(view: View) {
        when (view.id) {
            //工序
            R.id.label_gong_xu -> {
                showGongXuDialog()
            }
            //机台
            R.id.label_ji_tai -> {
                if (mGX.isEmpty()) {
                    showToast(getString(R.string.please_select_gong_xu))
                    return
                }
                mPresenter.getJiTaiFromServer(mGX)
            }
            //工艺
            R.id.cml_gong_yi -> {
                if (mGX.isEmpty()) {
                    showToast(getString(R.string.please_select_gong_xu))
                    return
                }
                mPresenter.getGongYiFromServer(mGX)
            }
            //班组
            R.id.cml_ban_zu -> {
                if (mGX.isEmpty()) {
                    showToast(getString(R.string.please_select_gong_xu))
                    return
                }
                mPresenter.getBanZuFromServer(mGX)
            }
            //不良原因
            R.id.img_right -> {
                mPresenter.getBuLiangFromServer()
            }
            //提交
            R.id.tv_commit -> {
                if (label_liangpin_shuliang?.getEditText().isNullOrEmpty()) {
                    showToast(R.string.input_liangpin_num)
                    return
                }
                if (DataUtil.toInt(label_liangpin_shuliang?.getEditText()) < 0) {
                    showToast(R.string.the_quantity_cannot_be_negative)
                    return
                }
                if (DataUtil.toInt(label_buliang_shuliang?.getEditText()) < 0) {
                    showToast(R.string.the_number_of_defects_cannot_be_negative)
                    return
                }
                if (DataUtil.toInt(
                        label_buliang_shuliang?.getEditWidget()?.text?.trim().toString()
                    ) > 0
                    && (label_bottom_buliang_yuanying?.getEditWidget()?.text?.toString()
                        ?: "").isEmpty()
                ) {
                    showToast(R.string.please_input_reson)
                    return
                }
                commit(true)
            }
        }
    }

    private fun commit(exit: Boolean) {
        if (label_scan?.getEditWidget()?.text?.toString().isNullOrEmpty()) return
        mPresenter.commit(
            barcode = label_scan?.getEditWidget()?.text?.toString() ?: "",
            pda = AppUtil.getIMEI(this),
            no1 = if (exit) label_gong_dan?.getContentWidget()?.text?.toString() ?: "" else "",
            no9 = label_bottom_buliang_yuanying?.getEditText() ?: "",
            no6 = mGX,
            no7 = mNo7,
            no8 = mNo8,
            no10 = mNo10,
            qty3 = DataUtil.toInt(
                label_buliang_shuliang?.getEditWidget()?.text?.toString() ?: ""
            ),
            qty4 = DataUtil.toInt(label_liangpin_shuliang?.getEditWidget()?.text?.toString() ?: ""),
            exit = exit
        )
    }

    private fun showGongXuDialog() {
        if (mGongXuPopupWindow?.isShowing == true) {
            return
        }
        if (mGongXuPopupWindow == null) {
            mGongXuPopupWindow = getNormalPopupWindow(mPresenter.mGongXuList) {
                mGX = mPresenter.mGongXuList[it].basId ?: ""
                label_gong_xu?.getContentWidget()?.text = mPresenter.mGongXuList[it].basName
                mPresenter.clearData()
                mNo7 = ""
                mNo8 = ""
                mNo10 = ""
                mGongYiPopupWindow = null
                mJiTaiPopupWindow = null
                mBanZuPopupWindow = null
                cml_ban_zu?.getContentWidget()?.text = ""
                cml_gong_yi?.getContentWidget()?.text = ""
                label_ji_tai?.getContentWidget()?.text = ""
                clearShowContent()
                mGongXuPopupWindow?.dismiss()
            }
        }
        mGongXuPopupWindow?.showAsDropDown(
            label_gong_xu.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    /**
     * 清除显示内容
     */
    private fun clearShowContent() {
        label_scan?.getEditWidget()?.clearFocus()
        label_buliang_shuliang?.getEditWidget()?.clearFocus()
        label_liangpin_shuliang?.getEditWidget()?.clearFocus()
        label_bottom_buliang_yuanying?.getEditWidget()?.clearFocus()
        clearBackContent()
    }

    /**
     * 清除返回内容
     */
    private fun clearBackContent(){
        label_scan?.getEditWidget()?.setText("")
        label_gong_dan?.getContentWidget()?.text = ""
        label_ke_hu?.getContentWidget()?.text = ""
        label_pin_ming?.getContentWidget()?.text = ""
        label_gui_ge?.getContentWidget()?.text = ""
        label_xing_hao?.getContentWidget()?.text = ""
        label_main_gong_xu?.getContentWidget()?.text = ""
        label_bottom_ji_tai?.getContentWidget()?.text = ""
        label_ban_zu?.getContentWidget()?.text = ""
        label_bottom_buliang_yuanying?.getEditWidget()?.setText("")
        label_gong_yi?.getContentWidget()?.text = ""
        label_po?.getContentWidget()?.text = ""
        label_gong_dan_liang?.getContentWidget()?.text = ""
        label_yibao_gongdan?.getContentWidget()?.text = ""
        label_liangpin_shuliang?.getEditWidget()?.setText("")
        label_buliang_shuliang?.getEditWidget()?.setText("")
    }

    private fun showJiTaiDialog() {
        if (mJiTaiPopupWindow?.isShowing == true) {
            return
        }
        if (mJiTaiPopupWindow == null) {
            mJiTaiPopupWindow = getNormalPopupWindow(mPresenter.mJiTaiList) {
                mNo7 = mPresenter.mJiTaiList[it].basId ?: ""
                label_ji_tai?.getContentWidget()?.text = mPresenter.mJiTaiList[it].basName
                mJiTaiPopupWindow?.dismiss()
            }
        }
        mJiTaiPopupWindow?.showAsDropDown(
            label_ji_tai.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun showGongYiDialog() {
        if (mGongYiPopupWindow?.isShowing == true) {
            return
        }
        if (mGongYiPopupWindow == null) {
            mGongYiPopupWindow = getNormalPopupWindow(mPresenter.mGongYiList) {
                mNo10 = mPresenter.mGongYiList[it].basId ?: ""
                cml_gong_yi?.getContentWidget()?.text = mPresenter.mGongYiList[it].basName
                mGongYiPopupWindow?.dismiss()
            }
        }
        mGongYiPopupWindow?.showAsDropDown(
            cml_gong_yi.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun showBanZuDialog() {
        if (mBanZuPopupWindow?.isShowing == true) {
            return
        }
        if (mBanZuPopupWindow == null) {
            mBanZuPopupWindow = getNormalPopupWindow(mPresenter.mBanZuList) {
                mNo8 = mPresenter.mBanZuList[it].basId ?: ""
                cml_ban_zu?.getContentWidget()?.text = mPresenter.mBanZuList[it].basName
                mBanZuPopupWindow?.dismiss()
            }
        }
        mBanZuPopupWindow?.showAsDropDown(
            cml_ban_zu.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun showBuLiangDialog() {
        if (mTeamGroupPopupWindow?.isShowing == true) {
            return
        }
        if (mTeamGroupPopupWindow == null) {
            mTeamGroupPopupWindow = getNormalPopupWindow(mPresenter.mBuLiangList) {
                label_bottom_buliang_yuanying?.getEditWidget()
                    ?.setText(mPresenter.mBuLiangList[it].basName)
                mTeamGroupPopupWindow?.dismiss()
            }
        }
        mTeamGroupPopupWindow?.showAsDropDown(
            label_bottom_buliang_yuanying.getEditWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun getNormalPopupWindow(
        dataList: List<ServerBean.GXInfo>,
        callback: (index: Int) -> Unit
    ): PopupWindow {
        return DialogUtil.getNormalPop(this, dataList, callback)
    }


    companion object {
        const val scanRequestCode = 100

        @JvmStatic
        fun startActivity(activity: Activity) {
            Intent(activity, GongXuCommitActivity::class.java)
                .apply {
                    activity.startActivity(this)
                }
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun dismissLoading() {
        dismissLoadingDialog(true)
    }

    override fun reportSuccess(dataInfo: ServerBean.GXReportResponse) {
        label_gong_dan?.getContentWidget()?.text = dataInfo.no1
        label_ke_hu?.getContentWidget()?.text = dataInfo.no2
        label_pin_ming?.getContentWidget()?.text = dataInfo.no3
        label_gui_ge?.getContentWidget()?.text = dataInfo.no4
        label_xing_hao?.getContentWidget()?.text = dataInfo.no5
        label_main_gong_xu?.getContentWidget()?.text = mPresenter.getGongXuTitle(dataInfo.no6 ?: "")
        label_bottom_ji_tai?.getContentWidget()?.text = mPresenter.getJiTaiTitle(dataInfo.no7 ?: "")
        label_ban_zu?.getContentWidget()?.text = mPresenter.getBanZuTitle(dataInfo.no8 ?: "")
        label_bottom_buliang_yuanying?.getEditWidget()?.setText(dataInfo.no9)
        label_gong_yi?.getContentWidget()?.text = mPresenter.getGongYiTitle(dataInfo.no10 ?: "")
        label_po?.getContentWidget()?.text = dataInfo.no11
        label_gong_dan_liang?.getContentWidget()?.text = dataInfo.qty1
        label_yibao_gongdan?.getContentWidget()?.text = dataInfo.qty2
        label_liangpin_shuliang?.getEditWidget()?.setText(dataInfo.qty4)
        label_buliang_shuliang?.getEditWidget()?.setText(dataInfo.qty3)
    }

    override fun reportFailed(message: String?) {
        showToast(if (message.isNullOrEmpty()) getString(R.string.request_failed) else message)
    }

    override fun onGongYiSuccess() {
        showGongYiDialog()
    }

    override fun onBanZuSuccess() {
        showBanZuDialog()
    }

    override fun onJiTaiSuccess() {
        showJiTaiDialog()
    }

    override fun onBuLiangSuccess() {
        showBuLiangDialog()
    }

    override fun actionSuccess() {
        showToast(R.string.commit_success)
        clearShowContent()
    }

    override fun actionFail(message: String?) {
        showToast(if (message.isNullOrEmpty()) getString(R.string.commit_failed) else message)
    }

    override fun exit() {
        supportFinishAfterTransition()
    }
}